package com.buddy.rpc.sdk.register;

import com.buddy.rpc.sdk.framework.Url;

import java.io.*;
import java.util.*;

/**
 * @author buddy
 * @date 2021/12/21
 */
public class RemoteRegister {

    /**
     * 注册中心存储
     */
    private static final Map<String, List<Url>> REGISTER = new HashMap<>();

    public static void register(String interfaceName, Url url) {
        List<Url> urls = Collections.singletonList(url);
        REGISTER.put(interfaceName, urls);
        saveFile();
    }


    public static Url getRandom(String interfaceName) {
        List<Url> urls = get(interfaceName);
        int i = new Random().nextInt(urls.size());
        return urls.get(i);
    }

    public static List<Url> get(String interfaceName) {
        Map<String, List<Url>> urlMap = getFile();
        return urlMap.get(interfaceName);
    }

    private static Map<String, List<Url>> getFile() {
        try (FileInputStream fis = new FileInputStream("temp.txt");
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            return (Map<String, List<Url>>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    private static void saveFile() {
        try (FileOutputStream fos = new FileOutputStream("temp.txt");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(REGISTER);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
